/*
 * Hibiscus is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * Hibiscus is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Hibiscus; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 * Copyright (C) 2003 Tetete - http://tetete.hu.
 */
package hu.tetete.hibiscus.taxontree;

import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import hu.tetete.hibiscus.DashboardActivity;
import hu.tetete.hibiscus.R;
import hu.tetete.hibiscus.dal.TaxonDao;
import hu.tetete.hibiscus.dal.TaxonDatabaseOpenHelper;
import hu.tetete.hibiscus.edittaxon.EditTaxonActivity;
import hu.tetete.hibiscus.model.Taxon;
import hu.tetete.hibiscus.model.TaxonLevel;
import hu.tetete.hibiscus.userfile.UserfileUtil;

/**
 * TODO javadoc.
 */
public final class TaxonTreeActivity extends Activity {

    private static final String TAG = TaxonTreeActivity.class.getName();

    private TaxonTreeExpandableListAdapter taxonTreeAdapter;
    private TaxonDao                       taxonDao;
    private Taxon                          taxon;

    /**
     * Possible Intent parameters.
     */
    public enum INTENT_EXTRA {
        /**
         * A taxon what the tree will display.
         */
        TAXON
    }

    /**
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.taxonDao = new TaxonDao(new TaxonDatabaseOpenHelper(this));
    }

    /**
     * @see android.app.Activity#onStart()
     */
    @Override
    protected void onStart() {
        super.onStart();

        final Intent incomeIntent = getIntent();
        this.taxon = incomeIntent == null || incomeIntent.getExtras() == null ? null : (Taxon)incomeIntent.getExtras().get(INTENT_EXTRA.TAXON.name());
        this.taxonTreeAdapter = new TaxonTreeExpandableListAdapter(this, buildStructure(this.taxonDao, taxon));


        final LayoutInflater     inflater         = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View               view             = inflater.inflate(R.layout.taxon_tree, null);
        final ImageView          taxonImage       = (ImageView)view.findViewById(R.id.taxonImage);
        final ExpandableListView taxonTreeList    = (ExpandableListView)view.findViewById(R.id.taxonTreeExpandableList);
        final View               homeButton       = view.findViewById(R.id.homeButton);
        final TextView           taxonNameField   = (TextView)view.findViewById(R.id.taxonName);
        final TextView           scienceNameField = (TextView)view.findViewById(R.id.scienceName);

        homeButton.setOnClickListener(new DashboardActivity.HomeButtonListener(this));
        taxonNameField.setText(taxon == null ? "Taxontree" : taxon.getName());
        scienceNameField.setText(taxon == null ? null : taxon.getScienceName());

        if (taxon != null) {
            final File photo = UserfileUtil.getTaxonPhoto(taxon);
            if (photo != null) {
                taxonImage.setImageURI(Uri.fromFile(photo));
            }
        }

        taxonTreeList.setAdapter(taxonTreeAdapter);
        taxonTreeList.setOnChildClickListener(new TaxonTreeOnChildClickListener());
        setContentView(view);

    }

    private EnumMap<TaxonLevel, List<Taxon>> buildStructure(final TaxonDao dbHandler, final Taxon taxon) {
        final EnumMap<TaxonLevel, List<Taxon>> results = new EnumMap<TaxonLevel, List<Taxon>>(TaxonLevel.class);
        final List<Taxon> children = dbHandler.getChildrenOfTaxon(taxon == null ? null : taxon.getId());
        for (final Taxon childTaxon : children) {
            final TaxonLevel taxonLevel = childTaxon.getTaxonLevel();
            final List<Taxon> levelTaxons = results.get(taxonLevel);
            if (levelTaxons == null) {
                final List<Taxon> newList = new ArrayList<Taxon>();
                newList.add(childTaxon);
                results.put(taxonLevel, newList);
            } else {
                levelTaxons.add(childTaxon);
            }
        }
        return results;
    }

    private class TaxonTreeOnChildClickListener implements ExpandableListView.OnChildClickListener {

    /**
     * @see android.app.ExpandableListActivity#onChildClick(android.widget.ExpandableListView, android.view.View, int, int, long)
     */
    @Override
    public boolean onChildClick(final ExpandableListView parent, final View view,
            final int groupPosition, final int childPosition, final long id) {
                //super.onChildClick(parent, view, groupPosition, childPosition, id);

    //        final Object o = getExpandableListAdapter().getChild(groupPosition, childPosition);
    //        final String keyword = String.valueOf(o);
    //        Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG).show();

    //        final Intent myIntent = new Intent(view.getContext(), BarniTestActivity.class);
    //        myIntent.putExtra(BarniTestActivity.TEXT_CONTENT_INTENT_EXTRA, (String)getExpandableListAdapter().getChild(groupPosition, childPosition));
    //        startActivity(myIntent);

    //        final Intent intent = new Intent(view.getContext(), BarniExpandableListActivity.class);
    //        intent.putExtra(BarniExpandableListActivity.INTENT_EXTRA.TAXON.name(), (Taxon)getExpandableListAdapter().getChild(groupPosition, childPosition));
    //        startActivity(intent);

            final Intent intent = new Intent(view.getContext(), TaxonTreeActivity.class);
            intent.putExtra(TaxonTreeActivity.INTENT_EXTRA.TAXON.name(), (Taxon)parent.getExpandableListAdapter().getChild(groupPosition, childPosition));
            startActivity(intent);

            return true;
        }
    }

    /**
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "RequestCode: " + requestCode + " ResultCode: " + resultCode);
    }
    /**
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        final MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.taxon_tree_menu, menu);
        /* Disables edit menu if there is no taxon - the program is at the root element */
//        final MenuItem editMenuItem = menu.findItem(R.id.editTaxonMenuItem);
//        editMenuItem.setEnabled(this.taxon != null);
        //TODO we should disable the add if the taxon is on the lowest level.
        return true;

    }

    /**
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case R.id.newTaxonMenuItem : {
                final Intent newTaxonIntent = new Intent(this, EditTaxonActivity.class);
                newTaxonIntent.putExtra(EditTaxonActivity.INTENT_EXTRA.PARENT_TAXON.name(), this.taxon);
                startActivity(newTaxonIntent);
                return true;
            }
            default : {
                return super.onOptionsItemSelected(item);
            }
        }

    }

}
